package Lab07.Q4;

//抽象迭代器，也可适用抽象类，并给每一个方法提供一个空的实现。

public class ShapeSequence {
    private final Shape[] shapes;
    int size;//当前size
    int fullSize;//最大size
    interface Iterator {
        boolean isEnd();

        Shape current();

        void moveNext();

        boolean equals(Object o);
    }
    public SequenceIterator iterator() {return new SequenceIterator();}
    private class SequenceIterator implements Iterator {
        private int cur;

        public SequenceIterator() {
            this.cur = 0;
        }

        @Override
        public boolean isEnd() {
            return this.cur + 1 == size;
        }

        @Override
        public Shape current() {
            if (isEnd())
                return null;
            return shapes[this.cur];
        }

        @Override
        public void moveNext() {

            if (isEnd())
                return;
            this.cur++;
        }

        public boolean equals(Object o) {
            if (this == o)
                return true;
            else if (o == null || getClass() != o.getClass())
                return false;
            SequenceIterator that = (SequenceIterator)o;
            return cur==that.cur;
        }
    }

    public ShapeSequence(int size) {
        this.fullSize = Math.max(size, 0);
        this.size = 0;
        //初始化Shape
        shapes = new Shape[this.fullSize];
    }

    public void add(Shape shape) {
        if (this.fullSize > this.size) {
            this.shapes[size] = shape;
            this.size++;
        }
    }

    public String toString() {
        StringBuilder s = new StringBuilder("[");
        for (Shape shape : shapes) {
            s.append(shape.getClass().getSimpleName()).append(",");
        }
        return s.substring(0,s.length()-1)+"]";
    }

}
